package com.sunwayworld.basemodule.framework.autotranslate.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sunwayworld.basemodule.framework.autotranslate.service.LimsI18NAutoTranslateService;
import com.sunwayworld.framework.context.ApplicationContextHelper;
import com.sunwayworld.framework.data.page.Page;
import com.sunwayworld.framework.data.page.PageRequest;
import com.sunwayworld.framework.data.page.Pageable;
import com.sunwayworld.framework.mybatis.mapper.MapperParameter;
import com.sunwayworld.framework.mybatis.mapper.MatchPattern;
import com.sunwayworld.framework.mybatis.mapper.SearchFilter;
import com.sunwayworld.framework.mybatis.page.PageRowBounds;
import com.sunwayworld.framework.spring.annotation.GikamBean;
import com.sunwayworld.framework.utils.StringUtils;
import com.sunwayworld.module.sys.code.bean.CoreCodeBean;
import com.sunwayworld.module.sys.code.bean.CoreCodeCategoryBean;
import com.sunwayworld.module.sys.code.service.CoreCodeCategoryService;
import com.sunwayworld.module.sys.code.service.CoreCodeService;
import com.sunwayworld.module.sys.i18n.bean.CoreI18nBean;
import com.sunwayworld.module.sys.i18n.bean.CoreI18nMessageBean;
import com.sunwayworld.module.sys.i18n.bean.LimsCoreI18nBean;
import com.sunwayworld.module.sys.i18n.service.CoreI18nMessageService;
import com.sunwayworld.module.sys.i18n.service.CoreI18nService;
import com.sunwayworld.module.sys.i18n.service.LimsCoreI18nService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @ClassName LimsI18NAutoTranslateServiceImpl
 * @Author zhoujq
 * @Date 2023/7/5
 * @Version 1.0
 **/
@Repository
@GikamBean
public class LimsI18NAutoTranslateServiceImpl implements LimsI18NAutoTranslateService {
    private static final Logger LOGGER = LoggerFactory.getLogger(LimsI18NAutoTranslateServiceImpl.class);

    @Autowired
    @Lazy
    LimsCoreI18nService limsCoreI18nService;

    @Autowired
    @Lazy
    CoreI18nService coreI18nService;

    @Autowired
    @Lazy
    CoreI18nMessageService coreI18nMessageService;

    @Autowired
    @Lazy
    RestTemplate restTemplate;

    @Autowired
    @Lazy
    CoreCodeService coreCodeService;

    @Autowired
    @Lazy
    CoreCodeCategoryService coreCodeCategoryService;

    @Override
    @Transactional
    public void autoTranslate() {
        String url = "http://fanyi.youdao.com/translate?";
        MapperParameter parameter = new MapperParameter();
        parameter.put("filterWithoutUS", "1");
//        parameter.put("ignoreLikes", "_CORE,LCDP,GIKAM");
//        parameter.setFilter(SearchFilter.instance().match("code","CRM").filter(MatchPattern.SC));
        Pageable pageable = PageRequest.of(1, 50);
        Page<LimsCoreI18nBean> needTransI18NPage = limsCoreI18nService.selectPagination(parameter, new PageRowBounds(pageable));
        List<LimsCoreI18nBean> needTransI18Ns = needTransI18NPage.getRows();
        if (needTransI18Ns == null) {
            return;
        }
        LOGGER.info("needTransI18Ns-----size={}", needTransI18Ns.size());
        if (needTransI18Ns.isEmpty()) {
            return;
        }
        LOGGER.info("needTransI18Ns-----{}", needTransI18Ns.stream().map(LimsCoreI18nBean::getCode).collect(Collectors.joining(",")));

        List<CoreI18nMessageBean> msgs = needTransI18Ns.stream().map(n -> {
            CoreI18nMessageBean messageBean = new CoreI18nMessageBean();
            String newUrl = url.concat("&doctype=json").concat("&type=ZH_CN2EN").concat("&i=").concat(n.getDefaultMessage());
            try {
                String reqs = restTemplate.getForObject(newUrl, String.class);
                JSONObject req = JSONObject.parseObject(reqs);
                assert req != null;
                String errorCode = req.getString("errorCode");
                if ("0".equals(errorCode)) {
                    JSONArray translateResult = req.getJSONArray("translateResult");
                    if (!translateResult.isEmpty()) {
                        JSONArray temp = translateResult.getJSONArray(0);
                        if (!temp.isEmpty()) {
                            messageBean.setMessage(temp.getJSONObject(0).getString("tgt"));
                            if (!StringUtils.isBlank(messageBean.getMessage())) {
                                messageBean.setMessage(messageBean.getMessage().substring(0, 1).toUpperCase().concat(messageBean.getMessage().substring(1)));
                            }
                            messageBean.setI18nConfigId("en-US");
                            messageBean.setI18nId(n.getId());
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
            return messageBean;
        }).filter(Objects::nonNull).collect(Collectors.toList());

        if (!msgs.isEmpty()) {
            List<Long> ids = ApplicationContextHelper.getNextIdentityList(msgs.size());
            for (int i = 0; i < msgs.size(); i++) {
                msgs.get(i).setId(ids.get(i));
            }
            coreI18nMessageService.getDao().insert(msgs);
        }

/*        List<CompletableFuture<CoreI18nMessageBean>> futures = needTransI18Ns.stream().map(n -> CompletableFuture.supplyAsync(() -> {
            CoreI18nMessageBean messageBean = new CoreI18nMessageBean();
            String newUrl = url.concat("&doctype=json").concat("&type=ZH_CN2EN").concat("&i=").concat(n.getDefaultMessage());
            try {
                String reqs = restTemplate.getForObject(newUrl, String.class);
                JSONObject req = JSONObject.parseObject(reqs);
                assert req != null;
                String errorCode = req.getString("errorCode");
                if ("0".equals(errorCode)) {
                    JSONArray translateResult = req.getJSONArray("translateResult");
                    if (!translateResult.isEmpty()) {
                        JSONArray temp = translateResult.getJSONArray(0);
                        if (!temp.isEmpty()) {
                            messageBean.setMessage(temp.getJSONObject(0).getString("tgt"));
                            messageBean.setI18nConfigId("en-US");
                            messageBean.setI18nId(n.getId());
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return messageBean;
        })).collect(Collectors.toList());

        CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();

        List<CoreI18nMessageBean> inserts = new ArrayList<>();
        futures.forEach(f -> {
            try {
                CoreI18nMessageBean messageBean = f.get();
                if (messageBean != null && messageBean.getI18nId() != null && !StringUtils.isBlank(messageBean.getMessage())) {
                    inserts.add(messageBean);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        if (!inserts.isEmpty()) {
            List<Long> ids = ApplicationContextHelper.getNextIdentityList(inserts.size());
            for (int i = 0; i < inserts.size(); i++) {
                inserts.get(i).setId(ids.get(i));
            }
            coreI18nMessageService.getDao().insert(inserts);
        }*/
    }

    @Override
    @Transactional
    public void autoAddI18NCode() {
        MapperParameter parameter = new MapperParameter();
        parameter.put("needI18NCode", "1");
        Page<CoreCodeCategoryBean> needI18NPage = coreCodeCategoryService.selectPagination(parameter, new PageRowBounds(PageRequest.of(1, 20)));
        List<CoreCodeCategoryBean> needI18Ns = needI18NPage.getRows();
        if (needI18Ns == null || needI18Ns.isEmpty()) {
            return;
        }
        // 选择内容的国际化编码暂时定为  LIMS.CORE_CODE.选择内容类型编码.
        List<String> categorys = needI18Ns.stream().map(CoreCodeCategoryBean::getId).collect(Collectors.toList());
        Map<String, List<CoreCodeBean>> codeGroupByCategorys = coreCodeService.selectListByFilter(SearchFilter.instance().match("CODECATEGORYID", categorys).filter(MatchPattern.OR)).stream().filter(c -> StringUtils.isBlank(c.getI18nCode())).collect(Collectors.groupingBy(CoreCodeBean::getCodeCategoryId));
        List<CoreI18nBean> insertI18NCode = new ArrayList<>();
        List<CoreI18nMessageBean> insertI18NMessage = new ArrayList<>();
        String codePattern = "^[a-zA-Z0-9_-]+$";
        List<CoreCodeBean> updateCodes = new ArrayList<>();
        codeGroupByCategorys.forEach((category, codes) -> {
            String i18NCodeFront = "LIMS.CORE_CODE.".concat(category.toUpperCase()).concat(".");
            CoreCodeCategoryBean categoryBean = needI18Ns.stream().filter(ct -> ct.getId().equals(category)).findAny().get();
            codes.forEach(code -> {
                String i18NCode = null;
                if (code.getCode().matches(codePattern)) {
                    i18NCode = i18NCodeFront.concat(code.getCode().toUpperCase());
                } else {
                    // 如果选择内容编码不是英文or数字，没办法  先取id
                    i18NCode = i18NCodeFront.concat(code.getId().toString());
                }
                CoreI18nBean i18nBean = new CoreI18nBean();
                i18nBean.setId(ApplicationContextHelper.getNextIdentity());
                i18nBean.setCode(i18NCode);
                i18nBean.setDefaultMessage(code.getCodeName());
                i18nBean.setDescription(categoryBean.getCodeCategoryName().concat(" ").concat(code.getCodeName()));
                insertI18NCode.add(i18nBean);

                CoreI18nMessageBean zhCN = new CoreI18nMessageBean();
                zhCN.setId(ApplicationContextHelper.getNextIdentity());
                zhCN.setI18nId(i18nBean.getId());
                zhCN.setI18nConfigId("zh-CN");
                zhCN.setMessage(code.getCodeName());
                insertI18NMessage.add(zhCN);

                code.setI18nCode(i18NCode);
                updateCodes.add(code);
            });
        });

        if (!insertI18NCode.isEmpty()) {
            coreI18nService.getDao().fastInsert(insertI18NCode);
        }
        if (!insertI18NMessage.isEmpty()) {
            coreI18nMessageService.getDao().fastInsert(insertI18NMessage);
        }
        if (!updateCodes.isEmpty()) {
            coreCodeService.getDao().fastUpdate(updateCodes, "i18nCode");
        }
    }
}
